import React from 'react';
import PropTypes from 'prop-types';
import { Dialog, Form, Input, Field, Checkbox, Balloon, Radio } from '@teamix/ui';
import { ButtonIcon } from '@alife/devops-ui';
import ListLoading from 'atComponents/ListLoading';
import docs from 'utils/docs';
import intl from '../../../../../../../../../../locale';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class EditPushRuletModal extends React.Component {
  static propTypes = {
    closeModal: PropTypes.func,
    id: PropTypes.number,
    edit: PropTypes.func,
  };

  static defaultProps = {
    closeModal: () => {},
    id: 0,
    edit: () => {},
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      submitting: false,
      // matchedBranchList: [],
    };
  }

  componentDidMount() {
    let commitmsgRule;
    let emailRule;
    this.props.getPushRuleById(this.props.id, (result) => {
      const commit_check_rules = [];
      let is_commit_check_enable = false;
      let commit_check_level = '';
      let is_force_push_disable = false;
      result.rule_infos.forEach((rule) => {
        if (rule.checker_name === 'CommitMessageChecker') {
          commitmsgRule = rule.extra_message;
        }
        if (rule.checker_name === 'CommitAuthorEmailChecker') {
          emailRule = rule.extra_message;
        }
        if (['CommitAuthorChecker', 'CommitCommitterChecker'].includes(rule.checker_name)) {
          if (rule.extra_message) {
            is_commit_check_enable = true;
            commit_check_level = rule.checker_type;
            commit_check_rules.push(rule.checker_name);
          }
        }

        if (rule.checker_name === 'ForcePushChecker') {
          is_force_push_disable = !!rule.extra_message;
        }
      });
      this.field.setValues({
        ref_name: result.ref_name,
        commit_message_checker: commitmsgRule,
        commit_email_checker: emailRule,
        commit_check_rules,
        is_commit_check_enable,
        commit_check_level,
        is_force_push_disable,
      });
    });
  }

  onClose = () => {
    this.props.closeModal();
  };

  handleOk = () => {
    if (this.state.submitting) return;
    this.field.validate((errors) => {
      if (!errors) {
        this.setState({ submitting: true });
        const formData = this.field.getValues();
        const {
          commit_check_rules,
          is_commit_check_enable,
          commit_check_level,
          is_force_push_disable,
        } = formData;
        const record = {
          ref_type: 'Branch',
          ref_name: formData.ref_name,
          rule_infos: [
            {
              checker_name: 'CommitMessageChecker',
              extra_message: formData.commit_message_checker || '',
            },

            {
              checker_name: 'CommitAuthorEmailChecker',
              extra_message: formData.commit_email_checker || '',
            },

            {
              checker_name: 'CommitAuthorChecker',
              extra_message:
                is_commit_check_enable && commit_check_rules.includes('CommitAuthorChecker')
                  ? 'on'
                  : '',
              checker_type: commit_check_level,
            },
            {
              checker_name: 'CommitCommitterChecker',
              extra_message:
                is_commit_check_enable && commit_check_rules.includes('CommitCommitterChecker')
                  ? 'on'
                  : '',
              checker_type: commit_check_level,
            },
            {
              checker_name: 'ForcePushChecker',
              extra_message: is_force_push_disable ? 'disabled' : '',
            },
          ],
        };

        this.props.edit(this.props.id, record, (isFail) => {
          if (!isFail) {
            this.field.reset();
          }
          this.setState({ submitting: false });
          this.onClose();
        });
      }
    });
  };

  checkValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.containers.editPushRule.editDialog.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  render() {
    const { init } = this.field;
    // const { matchedBranchList } = this.state;
    const { isLoadingDialog, record = {} } = this.props;
    const { ref_name = '' } = record;

    return (
      <Dialog
        title={
          <div>
            {intl.get({
              id: 'code-assets.containers.editPushRule.editDialog.EditPushRules',
              defaultMessage: '编辑推送规则',
            })}
          </div>
        }
        visible
        style={{ width: '600px' }}
        onOk={this.handleOk}
        onCancel={this.onClose}
        onClose={this.onClose}
        footerActions={['cancel', 'ok']}
        okProps={{ loading: this.state.submitting }}
      >
        {!isLoadingDialog ? (
          <Form {...formItemLayout} field={this.field} labelAlign="top">
            <div className="modal-item branch-name-item">
              {/* <FormItem
               label="分支"
               required
               help={
                 !matchedBranchList.length ? (
                   <div className="branch-name-tip">
                     支持通配符 ? 和 * ，如：*-stable 或 release/*
                   </div>
                 ) : (
                   ''
                 )
               }
              >
               <BranchAndTagSelect
                 value={ref_name}
                 autoComplete
                 onChange={(value) => {
                   this.onBranchChange('from', value);
                 }}
                 needTagSearch={false}
                 noDefaultValue
                 placeholder={'请输入分支或通配符规则'}
                 className="branch-name-input"
                 {...init('ref_name', {
                   initValue: ref_name,
                   rules: [{ required: true, message: '该项为必填项' }],
                 })}
               />
              </FormItem> */}
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.editPushRule.editDialog.Branch',
                  defaultMessage: '分支',
                })}
                required
                help={<div className="branch-name-tip">仅支持选择全部分支</div>}
              >
                <Input {...init('ref_name', { initValue: ref_name })} disabled />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.editPushRule.editDialog.SubmitComments',
                  defaultMessage: '提交注释',
                })}
                help={
                  <div className="branch-name-tip">
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.CommentsSubmittedMustConformTo',
                      defaultMessage:
                        '提交注释需符合正则表达式才允许推送，为空表示允许所有提交注释',
                    })}
                  </div>
                }
              >
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.containers.editPushRule.editDialog.ForExampleFixAZ',
                    defaultMessage: '如：^fix #[A-Z]+\\-[0-9]+',
                  })}
                  maxLength={500}
                  hasLimitHint
                  {...init('commit_message_checker')}
                />
              </FormItem>
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.editPushRule.editDialog.SubmitEmail',
                  defaultMessage: '提交邮箱',
                })}
                help={
                  <div className="branch-name-tip">
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.TheSenderSCommitterMailbox',
                      defaultMessage:
                        '提交人（Committer）邮箱需符合正则表达式匹配才允许推送，为空表示允许所有邮箱',
                    })}
                  </div>
                }
              >
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.containers.editPushRule.editDialog.ForExampleCodeupCom',
                    defaultMessage: '如：@codeup\\.com$',
                  })}
                  maxLength={500}
                  hasLimitHint
                  {...init('commit_email_checker')}
                />
              </FormItem>
            </div>
            <Form.Item {...init('is_force_push_disable')} label="" style={{ marginBottom: 0 }}>
              <Checkbox checked={this.field.getValue('is_force_push_disable')}>
                <span style={{ position: 'relative' }}>
                  {intl.get({
                    id: 'code-assets.containers.editPushRule.editDialog.ForcePushProhibitedForcePush',
                    defaultMessage: '禁止强制推送（Force Push）',
                  })}

                  <Balloon.Tooltip
                    trigger={
                      <ButtonIcon
                        name="question-line"
                        style={{ position: 'absolute', top: '-2px', marginLeft: '-4px' }}
                      />
                    }
                    align="t"
                    popupStyle={{
                      maxWidth: 'none',
                      width: 340,
                    }}
                  >
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.AfterThisFeatureIsEnabled',
                      defaultMessage: '开启后将不允许使用 git push -f 强制修改提交历史',
                    })}
                  </Balloon.Tooltip>
                </span>
              </Checkbox>
            </Form.Item>
            <Form.Item
              {...init('is_commit_check_enable', {
                props: {
                  onChange: (value) => {
                    if (value) {
                      this.field.setValue('commit_check_level', 'warn');
                      this.field.setValue('commit_check_rules', ['CommitAuthorChecker']);
                    } else {
                      this.field.setValue('commit_check_level', '');
                      this.field.setValue('commit_check_rules', []);
                    }
                  },
                },
              })}
              label=""
              style={{ marginBottom: 0 }}
            >
              <Checkbox checked={this.field.getValue('is_commit_check_enable')}>
                <span style={{ position: 'relative' }}>
                  {intl.get({
                    id: 'code-assets.containers.editPushRule.editDialog.TheCodeBelongsToThe',
                    defaultMessage: '代码属主检查',
                  })}

                  <Balloon
                    closable={false}
                    trigger={
                      <ButtonIcon
                        name="question-line"
                        style={{ marginLeft: 4, position: 'absolute', top: '-2px' }}
                      />
                    }
                    align="t"
                  >
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.CheckWhetherTheEmailInformation',
                      defaultMessage: '检查代码作者或者提交者邮箱信息是否与当前用户主邮箱一致。',
                    })}
                    <a target="_blank" href={docs('commit-check-repo')} rel="noreferrer">
                      {intl.get({
                        id: 'code-assets.containers.editPushRule.editDialog.HowToUse',
                        defaultMessage: '如何使用',
                      })}
                    </a>{' '}
                    ？
                  </Balloon>
                </span>
              </Checkbox>
            </Form.Item>
            {this.field.getValue('is_commit_check_enable') && (
              <React.Fragment>
                <Form.Item
                  className="push-rule-check-rules"
                  label={''}
                  labelAlign="left"
                  style={{ marginBottom: 0 }}
                >
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.CheckRules',
                      defaultMessage: '检查规则：',
                    })}
                  </span>
                  <Checkbox.Group
                    className="settings-repos-checkgroup"
                    {...init('commit_check_rules', {
                      rules: [
                        {
                          validator: this.checkValidator,
                        },
                      ],
                    })}
                  >
                    <Checkbox value={'CommitAuthorChecker'}>
                      {intl.get({
                        id: 'code-assets.containers.editPushRule.editDialog.CheckAuthorAuthor',
                        defaultMessage: '检查作者（Author）',
                      })}
                    </Checkbox>
                    <Checkbox value={'CommitCommitterChecker'}>
                      {intl.get({
                        id: 'code-assets.containers.editPushRule.editDialog.CheckSubmitterCommitter',
                        defaultMessage: '检查提交者（Committer）',
                      })}
                    </Checkbox>
                  </Checkbox.Group>
                </Form.Item>
                <Form.Item label={''} labelAlign="left">
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.editPushRule.editDialog.Limits',
                      defaultMessage: '限制级别：',
                    })}
                  </span>
                  <Radio.Group
                    className="settings-repos-checkgroup"
                    {...init('commit_check_level')}
                  >
                    <Radio value={'block'}>
                      {intl.get({
                        id: 'code-assets.containers.editPushRule.editDialog.NoPush',
                        defaultMessage: '禁止推送',
                      })}
                    </Radio>
                    <Radio value={'warn'}>
                      {intl.get({
                        id: 'code-assets.containers.editPushRule.editDialog.WarningOnlyPushAllowed',
                        defaultMessage: '仅警告，允许推送',
                      })}
                    </Radio>
                  </Radio.Group>
                </Form.Item>
              </React.Fragment>
            )}
          </Form>
        ) : (
          <ListLoading style={{ textAlign: 'center' }} />
        )}
      </Dialog>
    );
  }
}
